import { defineStore } from 'pinia'
import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo, verifyTokenApi } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const baseUrl = config.baseUrl

export const useUserStore = defineStore('user', {
	state: () => ({
	  token: getToken(),
	  name: storage.get(constant.name),
	  avatar: storage.get(constant.avatar) || '',
	  roles: storage.get(constant.roles),
	  permissions: storage.get(constant.permissions),
	  nickName: storage.get(constant.nickName)
	}),
	getters: {
	  getterToken: (state) => state.token,
	  getterAvatar: (state) => state.avatar,
	  getterName: (state) => state.name,
	  getterRoles: (state) => state.roles,
	  getterPermissions: (state) => state.permissions,
	  getterNickName: (state) => state.nickName
	},
	actions: {
	  // 登录
	  async login(userInfo) {
		const { username, password, code, uuid, loginType } = userInfo
		try {
		  const res = await login(username!=null?username.trim():"", password, code, uuid, loginType)
		  setToken(res.token)
		  this.token = res.token
		} catch (error) {
		  throw error
		}
	  },
	  // 获取用户信息
	  async getUserInfo() {
		try {
		  const res = await getInfo()
		  const user = res.user
		  const avatar = (user == null || user.avatar == "" || user.avatar == null) ?
			import("@/static/images/profile.jpg") : baseUrl + user.avatar
		  const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
		  const nickName = (user == null || user.nickName == "" || user.nickName == null) ? "" : user.nickName
		  const deptName = (user == null || user.deptName == "" || user.deptName == null) ? "" : user.deptName
  
		  this.roles = res.roles && res.roles.length > 0 ? res.roles : ['ROLE_DEFAULT']
		  this.permissions = res.permissions
		  this.username = username
		  this.avatar = avatar
		  this.nickName = nickName
		  this.deptName = deptName
		  storage.set(constant.nickName, nickName)
		  storage.set(constant.deptName, deptName)
		  return res
		} catch (error) {
		  throw error
		}
	  },
	  // 退出系统
	  async logout() {
		try {
		  await logout(this.token)
		  this.token = ''
		  this.roles = []
		  this.permissions = []
		  removeToken()
		  storage.clean()
		} catch (error) {
		  throw error
		}
	  },
	  setAvatar(avatarUrl) {
		this.avatar = avatarUrl;
		storage.set(constant.avatar, avatarUrl);
	  },
	  async verifyToken() {
		try {
		  console.log('开始验证token有效性')
		  const response = await verifyTokenApi(this.token)
		  console.log('token验证响应:', response)
		  return response.data.valid
		} catch (error) {
		  console.error('token验证请求失败:', error)
		  return false
		}
	  }
	}
  })

export default useUserStore
